import { getApp } from "@tarojs/taro";
import React from "react";


function Event(eventName, callback) {
  this.eventName = eventName;
  this.callback = callback;
}

Event.prototype.removeListener = function () {
  var { subscribers } = getApp().globalData;
  var index = subscribers.indexOf(this);
  if (index != -1) {
    subscribers.splice(index, 1);
  }
};

const EventEmitter = {
  addListener: function (eventName, callback) {
    var event = new Event(eventName, callback);
    var {subscribers} = getApp().globalData;
    subscribers.push(event);
    return event;
  },
  removeListener: function (event) {
    //event 类型： string || Event || Array
    var {subscribers} = getApp().globalData;
    var rm = function (e) {
      var index = subscribers.indexOf(e);
      if (index != -1) {
        subscribers.splice(index, 1);
      }
    };

    if (typeof event == "string") {
      subscribers.forEach(function (e, idx) {
        if (e.eventName == event) {
          subscribers.splice(idx, 1);
        }
      });
    } else if (event instanceof Event) {
      rm(event);
    } else if (event instanceof Array) {
      event.forEach(function (e) {
        EventEmitter.removeListener(e);
      });
    }
  },
  dispatch: function (eventName, param) {
    var {subscribers} = getApp().globalData;
    subscribers.forEach(function (event) {
      if (event.eventName === eventName) {
        event.callback && event.callback(param);
      }
    });
  },
  lookFunc: function (eventName) {
    let funcArr = [];
    var {subscribers} = getApp().globalData;
    subscribers.forEach(function (event) {
      if (event.eventName === eventName) {
        // event.callback && event.callback(param);
        funcArr.push(event.callback.toString());
      }
    });
    return funcArr;
  },
};

export default EventEmitter;
